package com.studentsys.servlet;



import com.studentsys.bean.Admin;
import com.studentsys.service.AdminService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/admin")
public class AdminServlet extends HttpServlet {
    //创建AdminService对象
    private AdminService as = new AdminService();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //处理中文乱码问题
        //设置服务器字符集为utf-8
//        req.setCharacterEncoding("utf-8");
        //设置浏览器也使用utf-8
//        resp.setContentType("text/html;charset=utf-8");
        //获取表单提交的数据（账号和密码）
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        Admin admin = as.login(username,password);

        //判断返回的用户对象是否为空
        if (admin!=null){
            //将用户保存到session中
            //设置登录控制
            HttpSession session = req.getSession();
            session.setAttribute("admin",admin);

            //登录成功,将用户名密码保存到cookie中
            String flag = req.getParameter("flag");
            if (flag!=null){
                //创建cookie
                Cookie cookie1 = new Cookie("username",admin.getUsername());
                Cookie cookie2 = new Cookie("password",admin.getPassword());
                //设置时间
                cookie1.setMaxAge(7*24*60*60);
                cookie2.setMaxAge(7*24*60*60);

                //响应cookie
                resp.addCookie(cookie1);
                resp.addCookie(cookie2);
            }
            //重定向
            resp.sendRedirect("student?method=findByPage");
            //请求转发
//            req.getRequestDispatcher("success.html").forward(req,resp);
        }else{
            //重定向
            resp.sendRedirect("login.jsp");
            //请求转发
//            req.getRequestDispatcher("fail.html").forward(req,resp);

        }
    }
    public void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.手动销毁session
        HttpSession session = req.getSession();
        session.invalidate();
        //2.跳转到登录页面
        resp.sendRedirect("login.jsp");
    }

}
